<?php

/**
 * Advanced array manipulation.
 *
 */
class Smithy_Collection_Array_Manipulation
{

    /**
     * Merges array of arrays by a key.
     *
     * @return array
     */
    public static function mergeArrayByKey($array, $keysToMerge, $key = 'id')
    {
    	if (!is_array($array))
    	   return $array;

    	$resultArray = array();

    	$actualKey = null;
    	foreach ($array as $arrayItem)
    	{
    		if (!is_array($arrayItem))
    		  return $array;

            if (!array_key_exists($key, $arrayItem))
              return $array;

    	    if ($arrayItem[$key] != $actualKey)
    	    {
                $actualKey = $arrayItem[$key];
                $resultArray[] = $arrayItem;

                $resRow = $resultArray[count($resultArray)-1];
                foreach ($resRow as $aKey => $aValue)
                {
                    if ($aKey !== $key and FALSE !== array_search($aKey, $keysToMerge))
                        $resRow[$aKey] = array($aValue);
                }
                $resultArray[count($resultArray)-1] = $resRow;
            }
            else
            {
                $resRow = $resultArray[count($resultArray)-1];
                foreach ($resRow as $aKey => $aValue)
                {
                    if ($aKey !== $key and FALSE !== array_search($aKey, $keysToMerge))
                    {
                        if ($aValue !== $arrayItem[$aKey])
                        {
                            if (is_array($resRow[$aKey]))
                                $resRow[$aKey][] = $arrayItem[$aKey];
                            else
                                $resRow[$aKey] = array($resRow[$aKey], $arrayItem[$aKey]);
                        }

                    }
                    $resultArray[count($resultArray)-1] = $resRow;
                }
            }

    	}

    	return $resultArray;

    }


}
